package com.song.cloud.hystrixPayment8001.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.song.cloud.hystrixPayment8001.service.hystrixService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @Author ZhangGuisong
 * @Date 2021/2/19-21:33
 */
@Service
public class hystrixServiceImpl implements hystrixService {
    @Override
    @HystrixCommand(fallbackMethod = "findError")
    public String getOk(Integer id) {
        int error=10/0;
        return "线程池"+Thread.currentThread().getName()+"info_ok,id:"+id+"\t";
    }

    @Override
    @HystrixCommand( fallbackMethod="timeOutFallBack" ,commandProperties = {@HystrixProperty(
            name="execution.isolation.thread.timeoutInMilliseconds" ,value="3000"
    )})
    public String getError(Integer id) {
        int timeout=5;
        //int timeout=10/0;
        try {
            TimeUnit.SECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池"+Thread.currentThread().getName()+"info_error,id:"+id+"\t";
    }
    //超时降级
    public String timeOutFallBack(Integer id){
        return   Thread.currentThread().getName()+ "程序繁忙，请求超时，请稍后重新访问"+id;
    }
    //程序异常降级
    public  String findError(Integer id){
        return Thread.currentThread().getName()+"程序访问出现异常，请稍后重新访问"+id;
    }

    /*
     * 服务熔断
     * */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback",
            commandProperties = {
                    @HystrixProperty(name="circuitBreaker.enabled" , value="true"),
                    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold" ,value="10"),
                    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
                    @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="60")
            }

    )
    public String  paymentCircuitBreaker(@PathVariable("id") Integer id){
        if(id<0){
            throw new RuntimeException("id 是负数");
        }
        String simpleUUID = IdUtil.simpleUUID();
        return  Thread.currentThread().getName()+"流水号"+simpleUUID;
    }
    public  String paymentCircuitBreakerFallback(@PathVariable("id")Integer id){
        return  Thread.currentThread().getName()+"id 不能是负数"+id;
    }
}
